package com.ooono.factorytest.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.ooono.factorytest.R;
import com.ooono.factorytest.model.TestItem;

import java.util.List;

public class TestItemAdapter extends RecyclerView.Adapter<TestItemAdapter.ItemViewHolder> {

    private Context mContext;
    private List<TestItem> mTestItems;

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    private OnItemClickListener mOnItemClickListener;

    public TestItemAdapter(Context context, List<TestItem> testItems) {
        this.mContext = context;
        this.mTestItems = testItems;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_test_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
        TestItem testItem = mTestItems.get(position);
        holder.nameTv.setText(testItem.getName());
        switch (testItem.getState()) {
            case TestItem.STATE_FAILURE:
                holder.nameTv.setBackgroundColor(mContext.getColor(R.color.red));
                holder.nameTv.setTextColor(mContext.getColor(R.color.white));
                break;
            case TestItem.STATE_SUCCESS:
                holder.nameTv.setBackgroundColor(mContext.getColor(R.color.green));
                holder.nameTv.setTextColor(mContext.getColor(R.color.white));
                break;
            case TestItem.STATE_UNKNOWN:
                holder.nameTv.setBackgroundColor(mContext.getColor(R.color.item_bg));
                holder.nameTv.setTextColor(mContext.getColor(R.color.white));
                break;
        }
        if (mOnItemClickListener != null) {
            holder.nameTv.setOnClickListener(v -> mOnItemClickListener.onItemClick(holder.nameTv, position));
        }
    }

    @Override
    public int getItemCount() {
        return mTestItems.size();
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {
        public TextView nameTv;

        public ItemViewHolder(View itemView) {
            super(itemView);
            nameTv = itemView.findViewById(R.id.tv_name);
        }
    }
}
